package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type supervisorOrder struct {
	iSupervisorOrder store.ISupervisorOrder
}

var SupervisorOrder = &supervisorOrder{
	iSupervisorOrder: mysql.SupervisorOrder,
}

func init() {
	Register(SupervisorOrder)
}

func (a *supervisorOrder) init() func() {
	return func() {}
}

// Create
func (a *supervisorOrder) Create(ctx context.Context, in *model.SupervisorOrderCreateRequest) error {
	var (
		err error
	)
	c := buildSupervisorOrder(in)
	_, err = a.iSupervisorOrder.Create(ctx, c)
	return err
}

// Update
func (a *supervisorOrder) Update(ctx context.Context, in *model.SupervisorOrderUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.ConsultId != nil {
		dict["consult_id"] = in.ConsultId
	}

	if in.Price != nil {
		dict["price"] = in.Price
	}

	if in.DeductCount != nil {
		dict["deduct_count"] = in.DeductCount
	}

	if in.DeductReason != nil {
		dict["deduct_reason"] = in.DeductReason
	}

	if in.SupervisorId != nil {
		dict["supervisor_id"] = in.SupervisorId
	}

	if in.Status != nil {
		dict["status"] = in.Status
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iSupervisorOrder.Update(ctx, in, dict)
}

// Delete
func (a *supervisorOrder) Delete(ctx context.Context, in *model.SupervisorOrderDeleteRequest) error {
	return a.iSupervisorOrder.Delete(ctx, in.Id)
}

// List
func (a *supervisorOrder) List(ctx context.Context, in *model.SupervisorOrderListRequest) (*model.SupervisorOrderListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.SupervisorOrder
		out   = &model.SupervisorOrderListResponse{}
	)

	if total, list, err = a.iSupervisorOrder.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.SupervisorOrdersEntityToDto(list)

	return out, nil
}

// Find
func (a *supervisorOrder) Find(ctx context.Context, in *model.SupervisorOrderInfoRequest) (*model.SupervisorOrderInfo, error) {
	var (
		err  error
		data *entity.SupervisorOrder
		out  = &model.SupervisorOrderInfo{}
	)

	if data, err = a.iSupervisorOrder.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.SupervisorOrderEntityToDto(data)
	return out, nil
}

// buildSupervisorOrder build entity
func buildSupervisorOrder(in *model.SupervisorOrderCreateRequest) *entity.SupervisorOrder {

	ety := &entity.SupervisorOrder{}

	ety.ConsultId = in.ConsultId

	ety.DeductReason = in.DeductReason

	ety.SupervisorId = in.SupervisorId

	ety.Status = in.Status

	ety.Price = in.Price

	ety.DeductCount = in.DeductCount

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
